package service

import (
	"barrage-go/common"
	"barrage-go/consts"
	"barrage-go/models"
	"barrage-go/proto/pb"
	"barrage-go/utils"
	"github.com/golang/protobuf/proto"
	"github.com/gorilla/websocket"
	"log"
	"strconv"
	"time"
)

func WebClientBarrageReq(msg []byte, ws *websocket.Conn) {
	barrageReq := pb.WebClientSendBarrageReq{}
	err := proto.Unmarshal(msg, &barrageReq)
	if err != nil {
		log.Println("解析客户端实时发送的弹幕请求信息发生异常:", err)
	}
	reqVideoId := barrageReq.VideoId
	if reqVideoId == "" {
		log.Println("客户端实时发送的弹幕视频id不存在")
		return
	}

	worker := utils.Worker{}
	userId, _ := strconv.ParseInt(barrageReq.UserId, 10, 64)
	videoId, _ := strconv.ParseInt(reqVideoId, 10, 64)

	videoTime := barrageReq.MsgVideoTime
	if videoTime < 1 {
		videoTime = 1
	}

	barrageMsg := models.BarrageMsg{
		Id:          worker.GetId(),
		UserId:      userId,
		VideoId:     videoId,
		MsgContent:  barrageReq.Msg,
		MsgPosition: barrageReq.MsgPosition,
		MsgColor:    barrageReq.MsgColor,
		VideoTime:   videoTime,
		DelFlag:     false,
		CreateTime:  time.Now(),
		UpdateTime:  time.Now(),
	}

	go models.SaveBarrageMsg(&barrageMsg)

	barrageResp := pb.WebClientSendBarrageResp{}
	barrageResp.Msg = barrageReq.Msg
	barrageResp.MsgColor = barrageReq.MsgColor
	barrageResp.MsgPosition = barrageReq.MsgPosition

	respBytes, _ := proto.Marshal(&barrageResp)
	clientResp := pb.Barrage{
		MsgType:   consts.WebClientBarrageResp,
		BytesData: respBytes,
	}
	client, _ := proto.Marshal(&clientResp)

	clients, ok := common.GetVideoMap(reqVideoId)
	if ok {
		for _, v := range clients {
			if ws != v {
				v.WriteMessage(websocket.BinaryMessage, client)
			}
		}
	}

}

func WebClientBarrageHistoryReq(msg []byte, ws *websocket.Conn) {
	historyReq := pb.WebClientBarrageHistoryListReq{}
	err := proto.Unmarshal(msg, &historyReq)
	if err != nil {
		log.Println("解析历史弹幕请求信息发生异常:", err)
	}
	videoId := historyReq.VideoId
	barrages := models.GetHistoryBarrages(videoId)

	historyResp := pb.WebClientBarrageHistoryListResp{}
	var barrageMsgList []*pb.BarrageHistoryMessage
	for _, v := range barrages {
		message := pb.BarrageHistoryMessage{}
		message.Msg = v.MsgContent
		message.MsgColor = v.MsgColor
		message.MsgPosition = v.MsgPosition
		message.SendTime = utils.SecToStrTime(v.VideoTime)
		message.VideoId = strconv.FormatInt(v.VideoId, 10)
		message.UserId = strconv.FormatInt(v.UserId, 10)
		message.CreateTime = v.CreateTime.Format("01-02 15:04")
		barrageMsgList = append(barrageMsgList, &message)
	}
	historyResp.List = barrageMsgList

	historyBytes, _ := proto.Marshal(&historyResp)
	clientResp := pb.Barrage{
		MsgType:   consts.WebClientBarrageHistoryResp,
		BytesData: historyBytes,
	}

	client, _ := proto.Marshal(&clientResp)
	err = ws.WriteMessage(websocket.BinaryMessage, client)

	if err != nil {
		log.Println("返回给客户端历史弹幕消息发生异常:", err)
	}

}
